using System.Collections.Generic;
using UnityEngine;

public class PlayerAfterImagePool : MonoBehaviour
{
    public GameObject _afterImagePrefab;

    private readonly Queue<GameObject> _availableObjects = new();

    public int Length { get; }

    private void Awake()
    {
        GrowPool();
    }

    private void GrowPool()
    {
        for (var i = 0; i < 10; i++)
        {
            var instanceToAdd = Instantiate(_afterImagePrefab);
            instanceToAdd.transform.SetParent(transform);
            AddToPool(instanceToAdd);
        }
    }

    public void AddToPool(GameObject instanceToAdd)
    {
        instanceToAdd.SetActive(false);
        _availableObjects.Enqueue(instanceToAdd);
    }

    public GameObject GetFromPool()
    {
        if (_availableObjects.Count == 0) GrowPool();

        var instance = _availableObjects.Dequeue();
        instance.SetActive(true);
        return instance;
    }

    #region Singleton

    private static PlayerAfterImagePool instance;

    public static PlayerAfterImagePool Instance
    {
        get
        {
            if (instance == null) instance = FindObjectOfType<PlayerAfterImagePool>();
            return instance;
        }
    }

    #endregion
}